var exportType = "";
$(document).ready(function(){
	$("#blockAppName").css("display","none");
	$("#blockServeiceIPAddr").css("display","none");
	$("#blockAuthGroup").css("display","none");
	$("#blockTable").css("display","block");
	$("#selectDB").css("display","block");
	$("#blockExportType").css("display","none");
	$("#clickSelected").change(function(){
		if($("#formType option:selected").val() == 1){
			$("#blockAppName").css("display","none");
			$("#blockServeiceIPAddr").css("display","none");
			$("#blockAuthGroup").css("display","none");
			$("#isReAdd").css("display","block");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
			$("#blockMember").css("display","block");
			$("#blockExportType").css("display","none");
		}
		if($("#formType option:selected").val() == 3){
			$("#blockServeiceIPAddr").css("display","none");
			$("#blockAppName").css("display","none");
			$("#blockAuthGroup").css("display","block");
			$("#blockAuthGroup").css("display","block");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
			$("#isReAdd").css("display","none");
			$("#blockMember").css("display","none");
			$("#blockExportType").css("display","none");
		}
		if($("#formType option:selected").val() == 5){
			$("#blockServeiceIPAddr").css("display","none");
			$("#blockAppName").css("display","none");
			$("#blockAuthGroup").css("display","block");
			$("#blockMember").css("display","block");
			$("#selectDB").css("display","none");
			$("#blockTable").css("display","none");
			$("#isReAdd").css("display","none");
			$("#blockExportType").css("display","none");
		}
		if($("#formType option:selected").val() == 7){
			ajaxAppInterfaceGetInfo(ipValue);
			$("#blockServeiceIPAddr").css("display","block");
			$("#blockAppName").css("display","block");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
			$("#blockAuthGroup").css("display","none");
			$("#blockMember").css("display","none");
			$("#isReAdd").css("display","none");
			$("#blockExportType").css("display","none");
		}
		if($("#formType option:selected").val() == 9){
			ajaxAppInterfaceGetInfo(ipValue);
			$("#blockServeiceIPAddr").css("display","none");
			$("#blockAppName").css("display","block");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
			$("#blockAuthGroup").css("display","none");
			$("#blockMember").css("display","none");
			$("#isReAdd").css("display","none");
			$("#blockExportType").css("display","none");
		}
		if($("#formType option:selected").val() == 11){
			ajaxAppInterfaceGetInfo(ipValue);
			$("#blockServeiceIPAddr").css("display","block");
			$("#blockAppName").css("display","block");
			$("#blockAuthGroup").css("display","none");
			$("#blockMember").css("display","none");
			$("#isReAdd").css("display","none");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","none");
			$("#blockExportType").css("display","none");
		}
		//导出表处理
		if($("#formType option:selected").val() == 13){
			exportType = $("#exportCheckDiv input:checked").val();
			$("#blockAppName").css("display","none");
			$("#blockServeiceIPAddr").css("display","none");
			$("#blockAuthGroup").css("display","none");
			$("#isReAdd").css("display","block");
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
			$("#blockMember").css("display","none");
			$("#blockExportType").css("display","block");
		}
	});
		
	//选择类型
	$("#exportCheckDiv").click(function(){
		exportType = $("#exportCheckDiv input:checked").val();
		if(exportType == 'et'){
			$("#selectDB").css("display","block");
			$("#blockTable").css("display","block");
		}else{
			$("#selectDB").css("display","none");
			$("#blockTable").css("display","none");
		}
		console.log(exportType);
	})
	
	
	$("#commitBtn").click(function(){
		var userName = $("#userName").val();
		if(isEmpty(userName)){
			swal("警告","申请人不能为空","warning");
	        return;
		}
		var ZN_NameReg = new RegExp(LTS.ReExp.ZnName);
		var result = userName.match(ZN_NameReg);
		if(null==result || 0==result.length){
			swal("警告","请输入中文姓名","warning");
	        return;
		}
		var emailReg = new RegExp(LTS.ReExp.email);
        var remark = $("#remark").val();
    	var usgae = $("#usgae").val();
    	var dbName;
    	var devApplyMember;
    	var deadLine;
    	var _gid;
    	var _gname;
    	var tableJsonStruct;
    	var tableAdd = new Array();
    	var tableDel = new Array();
    	var tableUpdate = new Array();
    	var tableSelect = new Array();
    	var formValue = $("#formType option:selected").val();
        if(formValue == 1){ //开发人员申请
        	dbName = $("#clickedDetailDBcontents").attr("dbname");
        	if(!dbName){
        		swal("警告","请选择库","warning");
                return;
        	}
        	devApplyMember = $.trim($("#member").val());
        	if(isEmpty(devApplyMember)){
                swal("警告","开通人员不能为空","warning");
                return;
            }
        	if(devApplyMember.indexOf(",") > 0){
        		var memberArray = devApplyMember.split(",");
        		for(var i in memberArray){
        			var _e = $.trim(memberArray[i]);
        			if(!emailReg.test(_e)){
        	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com 或 有多余 分隔符","warning");
        	            return;
        	        }
        		}
        	}else if(devApplyMember.indexOf("@") >1 && devApplyMember.indexOf(",") <= 0){
        		if(devApplyMember.split("@").length-1 <=1){
        			if(!emailReg.test($.trim(devApplyMember))){
        	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
        	            return;
        	        }
        		}else{
        			swal("警告","不同邮件之间请用英文 , 号进行分隔","warning");
    	            return;
        		}
        	}else if(devApplyMember.indexOf("@") <=0 && devApplyMember.indexOf(",") <= 0){
        		var _m = $.trim(devApplyMember);
    			if(!emailReg.test(_m)){
    	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
    	            return;
    	        }
        	}else if(devApplyMember.indexOf(",") <= 0){
        		var _a = $.trim(devApplyMember);
    			if(!emailReg.test(_a)){
    	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
    	            return;
    	        }
        	}
        	tableJsonStruct = eachDataBaseTableList(exportType);
        	deadLine = $("#deadline").val();
        	if(isEmpty(deadLine)){
        		swal("警告","使用期限不能为空","warning");
    	        return;
        	}
        }
        if(formValue == 3){
        	dbName = $("#clickedDetailDBcontents").attr("dbname");
        	if(!dbName){
        		swal("警告","请选择库","warning");
                return;
        	}
        	tableJsonStruct = eachDataBaseTableList(exportType);
        	_gid = $("#authGroup option:selected").val();
        	if(isEmpty(_gid)){
        		swal("警告","请选择权限组","warning");
                return;
        	}
        	_gname = $("#authGroup option:selected").attr("gname");
          }
        if(formValue == 5){
        	devApplyMember = $.trim($("#member").val());
        	if(isEmpty(devApplyMember)){
                swal("警告","开通人员不能为空","warning");
                return;
            }
        	if(devApplyMember.indexOf(",") > 0){
        		var memberArray = devApplyMember.split(",");
        		for(var i in memberArray){
        			var _e = $.trim(memberArray[i]);
        			if(!emailReg.test(_e)){
        	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com 或 有多余 分隔符","warning");
        	            return;
        	        }
        		}
        	}else if(devApplyMember.indexOf("@") >1 && devApplyMember.indexOf(",") <= 0){
        		if(devApplyMember.split("@").length-1 <=1){
        			if(!emailReg.test($.trim(devApplyMember))){
        	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
        	            return;
        	        }
        		}else{
        			swal("警告","不同邮件之间请用英文 , 号进行分隔","warning");
    	            return;
        		}
        	}else if(devApplyMember.indexOf("@") <=0 && devApplyMember.indexOf(",") <= 0){
        		var _m = $.trim(devApplyMember);
    			if(!emailReg.test(_m)){
    	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
    	            return;
    	        }
        	}else if(devApplyMember.indexOf(",") <= 0){
        		var _a = $.trim(devApplyMember);
    			if(!emailReg.test(_a)){
    	            swal("警告","邮箱格式不正确，正确格式为：xxx@gomeplus.com","warning");
    	            return;
    	        }
        	}
        	_gid = $("#authGroup option:selected").val();
        	if(isEmpty(_gid)){
        		swal("警告","请选择权限组","warning");
                return;
        	}
        	_gname = $("#authGroup option:selected").attr("gname");
        }
        var serverIpAddrVal;
        var appName;
        var appId;
        if(formValue == 7){
        	serverIpAddrVal = $("#serviceIpAddr").val();
        	if(isEmpty(serverIpAddrVal)){
        		swal("警告","请输入服务器ip地址","warning");
                return;
        	}
        	appId = $("#appName-select option:selected").val();
        	if(isEmpty(appId)){
        		swal("警告","请选择应用名称","warning");
                return;
        	}
        	appName = $("#appName-select option:selected").attr("app_name");
        	dbName = $("#clickedDetailDBcontents").attr("dbname");
        	if(!dbName){
        		swal("警告","请选择库","warning");
                return;
        	}
        	tableJsonStruct = eachDataBaseTableList(exportType);
        }
        if(formValue == 9){
        	appId = $("#appName-select option:selected").val();
        	if(isEmpty(appId)){
        		swal("警告","请选择应用名称","warning");
                return;
        	}
        	appName = $("#appName-select option:selected").attr("app_name");
        	dbName = $("#clickedDetailDBcontents").attr("dbname");
        	if(!dbName){
        		swal("警告","请选择库","warning");
                return;
        	}
        	tableJsonStruct = eachDataBaseTableList(exportType);
        }
        if(formValue == 11){
        	serverIpAddrVal = $("#serviceIpAddr").val();
        	if(isEmpty(serverIpAddrVal)){
        		swal("警告","请输入服务器ip地址","warning");
                return;
        	}
        	appId = $("#appName-select option:selected").val();
        	if(isEmpty(appId)){
        		swal("警告","请选择应用名称","warning");
                return;
        	}
        	appName = $("#appName-select option:selected").attr("app_name");
        	dbName = $("#clickedDetailDBcontents").attr("dbname");
        	if(!dbName){
        		swal("警告","请选择库","warning");
                return;
        	}
        }
        if(formValue == 13){
        	if(exportType == 'et'){
        		dbName = $("#clickedDetailDBcontents").attr("dbname");
            	if(!dbName){
            		swal("警告","请选择库","warning");
                    return;
            	}
        	}
        	tableJsonStruct = eachDataBaseTableList(exportType);
        	deadLine = $("#deadline").val();
        	if(isEmpty(deadLine)){
        		swal("警告","使用期限不能为空","warning");
    	        return;
        	}
        }
        if(isEmpty(usgae)){
    		swal("警告","权限用途不能为空","warning");
	        return;
    	}
        var project = $("#projectSelected option:selected").val();
        var url = getRoot() + '/datasource/commitFormDatasource';
    	var params = {'formType':formValue,'project':project,'appId':appId,'appName':appName,'serverIpAddr':serverIpAddrVal,'gid':_gid,'gname':_gname,'userName':userName,'devApplyMember':devApplyMember,'dbName':$("#clickedDetailDBcontents").attr("dbname"),'dbid':$("#clickedDetailDBcontents").attr("adid"),'tableStructJson':tableJsonStruct,'deadLine':deadLine,'remark':remark,'projectName':$("#projectSelected").val(),'usgae':usgae};
    	params['exportType'] = exportType;
    	$.post(url,params,function(data){
    		if(data.success){
    			swal("成功",""+data.msg,"success");
    			return;
    		}
    		if(data.failure){
    			swal("失败",""+data.msg,"error");
    			return;
    		}
    	});
	});
	loaddinDourceApplyDatabaseLists(ipValue,envirValue);
	searchDbNameByChange();
});

/**
 * 数据源申请调取接口数据
 * @param ipVal:ip地址
 * @param envVal:环境参数
 * @param groupType:组类型
 * @return ul的填充数据信息li
 * */
function loaddinDourceApplyDatabaseLists(ipVal,envVal){
	$.ajax({
		type : "post",
		async : true,
		url : "http://" + ipVal + "/mcenter/websql/api/database",
		data : {"env_type":envVal,"gtype":"APP"},
		dataType : 'jsonp',
		jsonp : 'callbackparam',
		jsonpCallback : "success_jsonpCallback",
		success : function(json) {
			var databaseLists = json;
			var optStr = "<option data-tokens='请选择数据库'>请选择数据库</option>";
			for(var i=0;i<databaseLists.length;i++){
				var name;
				if(databaseLists[i].db_type.toUpperCase() == 'ORACLE'){
					name = databaseLists[i].db_user;
				}else{
					name = databaseLists[i].db_name;
				}
				optStr += "<option class='dbName-opt' value='"
						+databaseLists[i].adid
						+"' dbtype='"
						+databaseLists[i].db_type
						+"' addr='"+databaseLists[i].ipaddr
						+"' port='"+databaseLists[i].db_port
						+"' dbuser='"+databaseLists[i].db_user
						+"' dbname='"+databaseLists[i].db_name
						+"' data-tokens='"+databaseLists[i].db_type+"@"+databaseLists[i].ipaddr+":"+databaseLists[i].db_port+"@"+name+"@"+databaseLists[i].app_name
						+"'>"+databaseLists[i].db_type+"@"+databaseLists[i].ipaddr+":"+databaseLists[i].db_port+"@"+name+"@"+databaseLists[i].app_name
						+"</option>";
			}
			$("#databaseName").empty();
			$("#databaseName").append(optStr);
			$("#databaseName").selectpicker('refresh');
		}
	});
}

function searchDbNameByChange(){
	$("#databaseName").on("change",function(){
		var matchDbName = [];
		var dbObj = {};
		if('请选择数据库'==$(this).find("option:selected").html()){
			return false;
		}
		dbObj['dbtype'] = $(this).find("option:selected").attr("dbtype");
		dbObj['dbname'] = $(this).find("option:selected").attr("dbname");
		dbObj['dbipaddr'] = $(this).find("option:selected").attr("addr");
		dbObj['port'] = $(this).find("option:selected").attr("port");
		dbObj['dbuser'] = $(this).find("option:selected").attr("dbuser");
		dbObj['adid'] = $(this).find("option:selected").val();
		matchDbName.push(dbObj);
		showRelatedDBName(matchDbName);
		showTableDetailInfo(dbObj['dbname'],dbObj['dbtype'],dbObj['dbipaddr'],dbObj['port'],dbObj['dbuser'],dbObj['adid']);
		dataTableNameClickEvent();
	})
	
}

function searchDbNameByInput(){
	$("#searchDBName").bind("input propertychange",function(){
		var inputName = $.trim($(this).val()).toLowerCase() ==""?0 : $.trim($(this).val()).toLowerCase();
		
		var matchDbName = [];
		$.each($("option.dbName-opt"),function(){
			var optDBName = $(this).attr("dbname").toLowerCase();
			if(optDBName.contains(inputName)){
				var dbObj = {};
				dbObj['dbtype'] = $(this).attr("dbtype");
				dbObj['dbname'] = $(this).attr("dbname");
				dbObj['dbipaddr'] = $(this).attr("addr");
				dbObj['port'] = $(this).attr("port");
				dbObj['dbuser'] = $(this).attr("dbuser");
				dbObj['adid'] = $(this).val();
				matchDbName.push(dbObj);
			}
			return true;
		});
		
		showRelatedDBName(matchDbName);
	});
	
}
/**
 * 输入框变化时，展示相应的匹配过的库名称
 * */
function showRelatedDBName(dbArray){
	if(0 == dbArray.length){ //无匹配隐藏
		$("#showRelatedDBNamesLiDiv").hide();
		return;
	}
	var liStr = "";
	for(var i in dbArray){
		liStr += "" +
        "<li class='searchDBName-li'>" +
        "<a> " +
        "<span class = 'text' dbname='"+dbArray[i].dbname+"' ipaddr='"
        +dbArray[i].dbipaddr+"' port='"
        +dbArray[i].port+"' dbtype='"
        +dbArray[i].dbtype+"' dbuser='"+dbArray[i].dbuser+"' adid='"+dbArray[i].adid+"'>" +
        dbArray[i].dbtype+"@"+dbArray[i].dbipaddr+":"+dbArray[i].port+"@"+dbArray[i].dbname +
        "</span> " +
        "<span class= 'glyphicon glyphicon-ok check-mark'>" +
        "</span>" +
        "</a>" +
        "</li>";
	}
	$("#showRelatedDBNamesLi").empty();
	$("#showRelatedDBNamesLi").append(liStr);
	clickTriaggerLiDbName();
}

/**
 *选中某一个表名 触发时间
 * */
function clickTriaggerLiDbName(){
	$(document).on("click",".searchDBName-li",function(){
		$("#showRelatedDBNamesLiDiv").hide();
		var dbname = $.trim($(this).find("span.text").html());
		var ipaddr = $.trim($(this).find("span.text").attr("ipaddr"));
		var port = $.trim($(this).find("span.text").attr("port"));
		var dbtype = $.trim($(this).find("span.text").attr("dbtype"));
		var adid = $.trim($(this).find("span.text").attr("adid"));
		var dbuser = $.trim($(this).find("span.text").attr("dbuser"));
		showTableDetailInfo(dbname,dbtype,ipaddr,port,dbuser,adid);
	});
}
/**
 * 展示表的详细信息内容
 * */
function showTableDetailInfo(dbname,dbtype,ipaddr,port,dbuser,adid){
	$("#clickedDetailDBcontents").attr("dbname",dbname);
	$("#clickedDetailDBcontents").attr("ip",ipaddr);
	$("#clickedDetailDBcontents").attr("port",port);
	$("#clickedDetailDBcontents").attr("dbtype",dbtype);
	$("#clickedDetailDBcontents").attr("dbuser",dbuser);
	$("#clickedDetailDBcontents").attr("adid",adid);
	$("#clickedDetailDBcontents").attr("dballinfo",dbtype+"@"+ipaddr+":"+port+"@"+dbname);
	$("#searchDBName").val(dbname);
	var url = getRoot() + '/datasource/getTableByAdmin';
	var DBType;
	if(dbtype == 'ORACLE'){
		DBType="3";
	}else if(dbtype == 'MYSQL'){
		DBType = "1";
	}else{
		DBType = "4";
	}
	var tableNameListHtml="<optgroup label=''><option selected='selected' data-tokens='请选择数据表'>请选择数据表</option></optgroup>";
	$.post(url,{"adId":adid},function(data){
		if(data.success){
			var indexCharArray = data.root;
			var optgroup="";
			for(var i in indexCharArray){
				optgroup="<optgroup label='"+i+"'>";
				var tableNames = indexCharArray[i];
				for(var j in tableNames){
					var optionHtml="<option data-tokens='"+tableNames[j]+"' value='"+tableNames[j]+"'>"+tableNames[j]+"</option>";
					optgroup+=optionHtml;
				}
				
				optgroup+="</optgroup>";
				tableNameListHtml+=optgroup;
			}
			$("#dataTableName").html(tableNameListHtml);
			$(".dataTableNameDiv .dataTableNameUl").empty();
			$("#dataTableName").selectpicker('refresh');
		}
		if(data.failure){
			$("#columnTableAuthType").empty();
			swal("错误",data.root,"error");
	        return;
		}
	});
}
function dataTableNameClickEvent(){
	$("#dataTableName").on("change",function(){
		var thisDataTable = $(this).find("option:selected").val();
		if('请选择数据表'==$(this).find("option:selected").html()){
			return false;
		}
		var dataBaseTableListObject=$(".dataTableNameDiv .dataTableNameUl li");
		if(dataBaseTableListObject.length>0){
			for(var i=0;i<dataBaseTableListObject.length;i++){
				var dataBaseObject=dataBaseTableListObject[i];
				var table_name=$(dataBaseObject).attr("tablename");
				if(table_name==thisDataTable){
					return false;
				}
			}
		}
		
		var _I = "<input type='checkbox' table='"+thisDataTable+"' class='addTableAuthBox' value='i'>增";
		var _D = "<input type='checkbox' table='"+thisDataTable+"' class='deleteTableAuthBox' value='d'>删";
		var _U = "<input type='checkbox' table='"+thisDataTable+"' class='updateTableAuthBox' value='u'>改";
		var _S = "<input type='checkbox' table='"+thisDataTable+"' class='selectTableAuthBox' value='s'>查";
		var _html="<li style='list-style:none;' tablename='"+thisDataTable+"'><span class='removeAttr'>&nbsp;</span><b>["+thisDataTable+"]</b><span class='checktables-oper'>(&nbsp;"+_I+_D+_U+_S+"&nbsp;)</span></li>";
		$(".dataTableNameDiv .dataTableNameUl").append(_html);
		clickRemoveAttrEvent();
	})
}
/**
 * ajax 应用接口调取应用名称信息
 * @param gtype :组类型 [APP/DEV]
 */
function ajaxAppInterfaceGetInfo(ipVal){
	$.ajax({
		type : "post",
		async : true,
		url : "http://" +ipVal+ "/mcenter/websql/api/application",
		data : {"gtype":"APP"},
		dataType : 'jsonp',
		jsonp : 'callbackparam',
		jsonpCallback : "success_jsonpCallback",
		success:function(data){
			var appNameLists = data;
			var optStr = "";
			for(var i=0;i<appNameLists.length;i++){
				var email = "";
				if(!appNameLists[i].owner_email){
					email = "无";
				}else{
					email = appNameLists[i].owner_email;
				}
				optStr += "<option value='"+appNameLists[i].apid+"' app_name='"+appNameLists[i].app_name+"' >"
				+appNameLists[i].app_name+" : "+ email +"</option>";
			}
			$("#appName-select").empty();
			$("#appName-select").append(optStr);
			$("#appName-select").selectpicker('refresh');
		}
	});
}
//遍历申请的数据库表集合
function eachDataBaseTableList(exportType){
	var dataBaseTableListObject=$(".dataTableNameDiv .dataTableNameUl li");
	if(exportType != 'eq'){
		if(''==$("#clickedDetailDBcontents").attr("dbname")){
			swal("错误","数据库不能为空");
			return false;
		}
		if(dataBaseTableListObject.length==0){
			swal("错误","数据库表不能为空");
			return false;
		}
	}
	var obj='[';
	var total=0;
	for(var i=0;i<dataBaseTableListObject.length;i++){
		var result;
		var dataBaseObject=dataBaseTableListObject[i];
		var table_name=$(dataBaseObject).attr("tablename");
		var dbType = $("#clickedDetailDBcontents").attr("dbtype");
		if(dbType.toLowerCase() == 'oracle'){
			result='{"schema": "'+$("#clickedDetailDBcontents").attr("dbuser")+'","table_name":"'+table_name+'",';
		}else{
			result='{"schema": "'+$("#clickedDetailDBcontents").attr("dbname")+'","table_name":"'+table_name+'",';
		}
		var count=0;
		$(dataBaseObject).find("input:checked").each(function(){
			var i='"'+$(this).val()+'":"Y",';
			result+=i; 
			count++;
			total++;
		});
		if(count>0){
			result = result.substring(0,result.lastIndexOf(","));
			obj +=result+"},";        		
		}
	}
	obj = obj.substring(0,(obj.lastIndexOf(",")));
	obj += "]";
	if(total==0){
		if(exportType == ''){
			swal("提示","请对表的操作做出勾选");
			return false;
		}else if(exportType == 'et'){
			var obj_et = '[{"schema": "'+$("#clickedDetailDBcontents").attr("dbuser")+'","table_name":"'+table_name+'","i":"N","d":"N","u":"N","s":"N"}]';
			return obj_et;
		}else if(exportType == 'eq'){
			var obj_eq = '[{"schema": "'+$("#clickedDetailDBcontents").attr("dbuser")+'","table_name":"'+"无"+'","i":"N","d":"N","u":"N","s":"N"}]';
			return obj_eq;
		}
	}
	return obj;
}
function clickRemoveAttrEvent(){
	$(".removeAttr").on("click",function(){
		var thisli=$(this).parent("li");
		$(thisli).remove();
	})
}